package com.project.base.common;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import java.math.BigDecimal;

public class NumberUtil {

    private static final Logger log = Logger.getLogger(NumberUtil.class);

    /**
     * 将字符串转换成Double
     *
     * @param value
     * @param newScale
     * @return
     */
    public static Double parseStr2Double(String value, int newScale) {

        if (StringUtils.isBlank(value) || "NaN".equals(value) || newScale < 0)
            return 0d;

        try {
            BigDecimal bd = new BigDecimal(value);
            return bd.setScale(newScale, BigDecimal.ROUND_HALF_UP).doubleValue();
        } catch (Exception e) {
            log.error("数据格式转换错误");
            return 0d;
        }
    }

    /**
     * 默认将字符串转换成两位小数点的Double
     *
     * @param value
     * @return
     */
    public static Double parseStr2Double(String value) {
        return parseStr2Double(value, 2);
    }

    public static void main(String[] args) {
        System.out.println(parseStr2Double("7.907893423"));
    }
}
